//
// Authenticate_LDAP.cpp
// libprotea
// Tools Library for the Protea Project / Functionality for user authentication via LDAP
// Copyright (C) 2003, 2004, 2005 eXegeSys, Inc.
// Copyright (C) 2008 Bruce A. James
//
// This program is part of the Protea Project.
//
// The Protea Project is free software; you can redistribute it and/or modify it 
// under the terms of the GNU General Public License as published by the 
// Free Software Foundation, either version 3 of the License, or (at your 
// option) any later version.
//
// The Protea Project is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
// for more details.
// 
// You should have received a copy of the GNU General Public License along 
// with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// Please send correspondence to:
// 
// theproteaproject@gmail.com
//

#include "../defines.h"
#include "AppInterface.h"
#include "security.h"

#include "../defns.h"
using namespace ProteaApp1;

#ifdef USE_LDAP
#include <ldap.h>
#endif

bool XCAuthenticate::AuthenticateLDAP( XCCredentials* creds, char* password ) {
	bool result = false;
	printf( "AuthenticateLDAP: user='%s'\n", creds->GetUserName() );

#ifdef USE_LDAP
	LDAP* session;
	LDAPMessage* res;

	// Ensure that we have been supplied a server name
	if (!*auth_parameter) {
		// Return an error to the system
		RAISETOOLSERROR_1PARM( ERR_AUTHENTICATION_ERROR, ERR_AUTH_PARAMETER );
	};

	// Initialize the session
	session = ldap_init( auth_parameter, LDAP_PORT );
	if (session) {
		// Attempt a bind, if successful, then the password is correct
		long hr = ldap_bind_s( session, creds->GetUserName(), password, LDAP_AUTH_SIMPLE );
		if (hr == LDAP_SUCCESS)
			result = true;

		// Unbind
		ldap_unbind( session );
	} else {
		RAISETOOLSERROR_1PARM( ERR_AUTHENTICATION_ERROR, ERR_AUTH_PARAMETER );
	};
#endif

	return result;
};
